package com.zj.leetcode.easy.tree;

/**
 * @program: algorithm
 * @description: 二叉树的直径
 * 543 diameter-of-binary-tree
 * @author: Zhang Bo
 * @create: 2022-06-06 10:34:42
 **/
public class DiameterOfBinaryTree {
    public static void main(String[] args) {
        Solution solution = new DiameterOfBinaryTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
//
//        public int diameterOfBinaryTree(TreeNode root) {
//            if (root == null || (root.left == null && root.right == null)) {
//                return 0;
//            }
//            int left = 0;
//            if (root.left != null) {
//                left = afterOrder(root.left) + 1;
//            }
//
//            int right = 0;
//            if (root.right != null) {
//                right = afterOrder(root.right) + 1;
//            }
//
//            return left + right;
//        }
//
//        public int afterOrder(TreeNode root) {
//            if (root == null || root.left == null && root.right == null) {
//                return 0;
//            }
//
//            int left = root.left == null ? 0 : afterOrder(root.left) + 1;
//
//            int right = root.right == null ? 0 : afterOrder(root.right) + 1;
//
//            return Math.max(left, right);
//        }


        public int diameterOfBinaryTree(TreeNode root) {
            if (root == null) {
                return 0;
            }


            afterOrder(root);
            return max;
        }

        int max = 0;
        public int afterOrder(TreeNode root) {
            if (root.left == null && root.right == null) {
                return 0;
            }

            int left = root.left == null ? 0 : afterOrder(root.left) + 1;

            int right = root.right == null ? 0 : afterOrder(root.right) + 1;

            max = Math.max(left + right, max);

            return Math.max(left, right);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
